/*
 * Copyrighted (C) Justin M. Wray - http://www.justinwray.com
 * 
 * Reddit Widget contains some derived work from the "The Android Open Source Project".
 * The Android project is released under the Apache License, Version 2.0.
 * Any code derived from the Android project is released under the Apache License, Version 2.0.
 * All other code is released under the GNU Public License, version 3.0.
 * Please follow the license corresponding to the code you are modifying and/or distributing.
 * 
 * GPL:
 * 
 *  This file is part of Reddit Widget.
 *  
 *  Reddit Widget is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Reddit Widget is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Reddit Widget.  If not, see <http://www.gnu.org/licenses/>.
 *
 * APL:
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  
 */

package com.jwray.redditwidget;

import com.jwray.redditwidget.RedditWidgetHelper.ApiException;
import com.jwray.redditwidget.RedditWidgetHelper.ParseException;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class RedditWidget extends AppWidgetProvider {
	public static int widgetId = 0;
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
    	widgetId = appWidgetIds[0];
        // To prevent any ANR timeouts, we perform the update in a service
        context.startService(new Intent(context, UpdateService.class));
    }
    
    public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
            int appWidgetIds) {
    	
        // To prevent any ANR timeouts, we perform the update in a service
        context.startService(new Intent(context, UpdateService.class));

        // Tell the widget manager
        //appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    
    public static class UpdateService extends Service {
        @Override
        public void onStart(Intent intent, int startId) {
            RemoteViews updateViews = buildUpdate(this);
            
            // Push update for this widget to the home screen
            ComponentName thisWidget = new ComponentName(this, RedditWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }

        public RemoteViews buildUpdate(Context context) {   	
        	//Pick out month names from resources
            Resources res = context.getResources();
            
            String pageURL = res.getString(R.string.template_content_url);
                
            SharedPreferences prefs = context.getSharedPreferences("com.jwray.redditwidget.RedditWidget", 0);
            String subredditPref = prefs.getString("config_" + widgetId, null);
            if (subredditPref != null) {
            	pageURL = res.getString(R.string.template_content_domain) + subredditPref + 
            		res.getString(R.string.template_content_ext);
            } else {
            	pageURL = res.getString(R.string.template_content_url);
            }
            
            RemoteViews updateViews = null;
            String[] pageContent = new String[]{"Reddit Error", "", "", ""};
            
            try {
                RedditWidgetHelper.prepareUserAgent(context);
                pageContent = RedditWidgetHelper.getPageContent(pageURL);
            } catch (ApiException e) {
                Log.e("WordWidget", "Couldn't contact API", e);
            } catch (ParseException e) {
                Log.e("WordWidget", "Couldn't parse API response", e);
            }
            
            if (pageContent.length > 0) {
                // Build an update that holds the updated widget contents
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_content);
                
            	String storyTitle = pageContent[0];
            	String storyLink = pageContent[1];
            	String storyAuthor = "Submitted By: " + pageContent[2];
            	String storyComments = "Comments: " + pageContent[3];
                updateViews.setTextViewText(R.id.story_title, storyTitle);
                updateViews.setTextViewText(R.id.story_author, storyAuthor);
                updateViews.setTextViewText(R.id.story_comments, storyComments);
                
                // When user clicks on widget, goto reddit page
                String definePage = res.getString(R.string.template_define_url,storyLink);
                Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(definePage));
                PendingIntent pendingIntent = PendingIntent.getActivity(context,
                        0 /* no requestCode */, defineIntent, 0 /* no flags */);
                updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent);
                
            } else {
                // Didn't find story? So show error message
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_message);
                CharSequence errorMessage = context.getText(R.string.widget_error);
                updateViews.setTextViewText(R.id.message, errorMessage);
            }
            return updateViews;
        }
        
        @Override
        public IBinder onBind(Intent intent) {
            // We don't need to bind to this service
            return null;
        }
    }
}
